package com.xuan.yupao.manager;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class OnlineUserManager {

    private final Map<Long, WebSocketSession> userManagerMap = new ConcurrentHashMap<>();

    public void online(Long userId, WebSocketSession webSocketSession) {
        // 查看用户是否已经在线
        if (userManagerMap.get(userId) != null) {
            log.info("用户处于在线状态,上线失败!");
            return;
        }
        userManagerMap.put(userId, webSocketSession);
        log.info("[online] 用户" + userId + "上线!");
    }

    public void offline(Long userId, WebSocketSession webSocketSession) {
        WebSocketSession existSession = userManagerMap.get(userId);
        if (existSession == webSocketSession) {
            // 当两个 websocketSession 是同一个时才真正进行下线
            userManagerMap.remove(userId);
            log.info("[offline] 用户" + userId + "下线!");
        }
    }

    public WebSocketSession getWebSocketSession(Long userId) {
        return userManagerMap.get(userId);
    }


    public Map<Long, WebSocketSession> getUserManagerMap() {
        return userManagerMap;
    }
}
